//
//  PayViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/16.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "PayViewController.h"
#import "PayTableViewCell.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthV2Info.h"
#import "OrderProductPay.h"
#import "payRequsestHandler.h"
#import "PaySuccessViewController.h"
static NSString * cellIdentify = @"PayTableViewCell";
@interface PayViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *banksInfoArray;
@property(nonatomic,strong)NSIndexPath * bankIndex;
@property (weak, nonatomic) IBOutlet UIButton *maskView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UIButton *cancleButton;
@property (weak, nonatomic) IBOutlet UIButton *sureButton;

@property(nonatomic,strong)NSString * leftMoney;
@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hadPay) name:@"hadPay" object:@"1"];
    
    _leftMoney = @"0.00";
    _banksInfoArray =[@[@[@{@"image":@"pay1",@"name":@"电子钱包"}],@[@{@"image":@"pay2",@"name":@"支付宝"},@{@"image":@"pay3",@"name":@"微信支付"},@{@"image":@"pay4",@"name":@"银联在线支付"}],@[@{@"image":@"pay5",@"name":@"中国工商银行"},@{@"image":@"pay6",@"name":@"中国农业银行"},@{@"image":@"pay7",@"name":@"中国银行"}]] mutableCopy];
    if(_type == 3){//充值订单
        [_banksInfoArray removeObjectAtIndex:0];
    }else{
        [self getPersonalLeftMoney];
    }
    [self initViewLayout];
    
    //保存订单id
    if (self.payId) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setObject:self.payId forKey:@"orderId"];
        [Common setMutableData:data];
    }
    // Do any additional setup after loading the view.
     [WXApi registerApp:APP_ID withDescription:@"demo 2.0"];
}
#pragma mark  布局调整--=========================================
- (void)initViewLayout{
    //功能栏
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.tableView];
    [self adaptiveViewLayout:self.passwordView];
    
    _passwordView.layer.cornerRadius = 6*VerticalRatio();
     _passwordField.layer.cornerRadius = 4*VerticalRatio();
    _passwordField.leftViewMode = UITextFieldViewModeAlways;
    _passwordField.leftView = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 10, 43), NO)];
    _cancleButton.layer.cornerRadius = 20*VerticalRatio();
     _sureButton.layer.cornerRadius = 20*VerticalRatio();
    //注册
    [self.tableView registerClass:[PayTableViewCell class]  forCellReuseIdentifier:cellIdentify];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

- (void)hadPay{
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark  ====关闭输入密码view
- (IBAction)closePasswordView:(id)sender {
    _passwordField.text = @"";
    _maskView.hidden = YES;
    _passwordView.hidden = YES;
    [self hideKeyBoard];
}
#pragma mark  ====余额支付确认密码
- (IBAction)surePassword:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_payId forKey:@"outTradeNo"];
    NSDate * date = [NSDate date];
    NSDateFormatter * dateformatter = [[NSDateFormatter alloc]init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * time = [dateformatter stringFromDate:date];
    [dic setObject:time forKey:@"payTime"];
    [dic setObject:[Common shaEncrypt:_passwordField.text] forKey:@"mepuPayPwd"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_payOrderByEpurse withHttpType:@"POST" withTag:SX_SX_payOrderByEpurse];
    
}

#pragma mark == 请求个人钱包余额
- (void)getPersonalLeftMoney{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_getEpurse withHttpType:@"POST" withTag:SX_SX_getEpurse];
}


#pragma mark ==== 支付
- (IBAction)payHandel:(id)sender {
    //支付宝配置信息
    [self getPaymentDetailInfo];
}
#pragma   mark  请求支付配置信息 ======================================
- (void)getPaymentDetailInfo{
//    self.view.userInteractionEnabled = NO;
    
    //支付宝
    if (_bankIndex.section==1 && _bankIndex.row==1) {
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"getAlipayInfo" forKey:@"method"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_getAlipayInfo withHttpType:@"POST" withTag:SX_getAlipayInfoTag];
    }else if (_bankIndex.section==1 && _bankIndex.row==2){
        //微信
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"getWxpayInfo" forKey:@"method"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_getWxpayInfo withHttpType:@"POST" withTag:SX_getWxpayInfoTag];
    }
    
    if (!_bankIndex) {
        [[CWHUDTips sharedInstance]showTips:@"请选择支付方式"];
    }else{
        if (_type!=3) {//没余额支付
            if (_bankIndex.section == 0) {//选择了余额支付
                _maskView.hidden = NO;
                _passwordView.hidden = NO;
                [_passwordField becomeFirstResponder];
            }else if (_bankIndex.section==1&&_bankIndex.row==1){//支付宝
                [self zfbPay];
            }else if (_bankIndex.section==1&&_bankIndex.row==2){//微信支付
                [self getWeixinInfo];
            }
        }else{//有余额支付
            if (_bankIndex.section==0&&_bankIndex.row==1){//支付宝
                [self zfbPay];
            }else if (_bankIndex.section==0&&_bankIndex.row==2){//微信支付
                [self getWeixinInfo];
            }
        }
    }
 
    
}
#pragma Mark====== 获取微信支付配置信息
- (void)getWeixinInfo{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
  
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_getWxpayInfo withHttpType:@"POST" withTag:SX_SX_getWxpayInfo];
}


#pragma -===== 获取支付宝配置信息
- (void)zfbPay{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_getAlipayInfo withHttpType:@"POST" withTag:SX_SX_getAlipayInfo];
}

#pragma   mark  跳转支付宝支付======================================
- (void)userAlibabaPaymentClick:(NSDictionary *)payDta{
    //实例并初始化订单信息
    OrderProductPay *product = [[OrderProductPay alloc] init];
    product.subject = self.payOrderName;
    product.body = self.payOrderName;
    product.price = [self.payOrderPrice floatValue];
    
    NSString *partner = [payDta objectForKey:@"payPartner"];
    NSString *seller = [payDta objectForKey:@"paySellAccount"];
    NSString *privateKey = [payDta objectForKey:@"payPrivate"];
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = _payId; //订单ID（由商家自行制定）
    order.productName = product.subject; //商品标题
    order.productDescription = product.body; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",product.price]; //商品价格
    order.notifyURL =  [payDta objectForKey:@"AlipayNotifyUrl"]; //回调URL
    //    order.notifyURL = @"http://www.baidu.com";
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"PeopleStreet";
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
                //传递支付成功信息
                //支付成功
                [self paymentWenxinAndZhifubaoSuccess:@"1"];
            }
        }];
        
    }
}
//支付成功


#pragma   mark  跳转微信支付====
- (void)sendPay_demo:(NSDictionary *)payDta
{
    //创建支付签名对象
    payRequsestHandler *req = [[payRequsestHandler alloc] init];
    //初始化支付签名对象
    [req init:[payDta objectForKey:@"payAppId"] mch_id:[payDta objectForKey:@"wxmchid"]];
    //设置密钥
    [req setKey:[payDta objectForKey:@"payAppKey"]];
    
    //}}}
    //组装支付参数数据
    NSMutableDictionary *payData = [NSMutableDictionary dictionary];
    [payData setObject:[payDta objectForKey:@"payAppId"] forKey:@"wxappid"];
    [payData setObject:[payDta objectForKey:@"payMchId"] forKey:@"wxmchid"];
    [payData setObject:[payDta objectForKey:@"payAppKey"] forKey:@"wxkey"];
    [payData setObject:[payDta objectForKey:@"payNotifyUrl"] forKey:@"WXNotifyUrl"];
    [payData setObject:self.payOrderName forKey:@"orderName"];
    [payData setObject:_payId forKey:@"ordernumber"];
    [payData setObject:self.payOrderName forKey:@"orderContent"];
    [payData setObject:self.payOrderPrice forKey:@"orderPrice"];
    //获取到实际调起微信支付的参数后，在app端调起支付
    NSMutableDictionary *dict = [req sendPay_demo:payData];
    
    if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        
        [self alert:@"提示信息" msg:debug];
        
        //        NSLog(@"%@\n\n",debug);
    }else{
        //        NSLog(@"%@\n\n",[req getDebugifo]);
        //[self alert:@"确认" msg:@"下单成功，点击OK后调起支付！"];
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [dict objectForKey:@"appid"];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        [WXApi sendReq:req];
        
    }
}

//微信支付成功回调
-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                //                strMsg = @"支付结果：成功！";
                //                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                //传递支付成功信息
                
                
                //支付成功
                [self paymentWenxinAndZhifubaoSuccess:@"2"];
                
                
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！"];
                //                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                break;
        }
    }
}



//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
    
}


#pragma mark   ====== 第三方支付成功调支付接口
- (void)paymentWenxinAndZhifubaoSuccess:(NSString *)payType{
     NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    [dic setObject:locationString forKey:@"payTime"];
    [dic setObject:payType forKey:@"payment"];
    
    [dic setObject:@"" forKey:@"tradeNo"];
    NSMutableDictionary *data = [Common getMutableData];
    [dic setObject:[data objectForKey:@"orderId"] forKey:@"outTradeNo"];
    if (!self.shareApi) {
        self.shareApi=[LQRequestApi sharedInstance];
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_payOrder withHttpType:@"POST" withTag:SX_payOrderTag];
  
   
    
}
#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _banksInfoArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 7;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * array = _banksInfoArray[section];
    return array.count+1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44*VerticalRatio();
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify forIndexPath:indexPath];
    if (!cell) {
        cell = [[PayTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }

    if (indexPath.row == 0) {
        NSArray * names = @[@"电子钱包",@"快捷支付",@"网银支付"];
        if (_type==3) {
            names = @[@"快捷支付",@"网银支付"];
        }
       UILabel * label =  [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(14, 0, 100, 44), NO)];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = names[indexPath.section];
               label.textColor = [UIColor colorWithWhite:0.463 alpha:1.000];
        label.font = [UIFont systemFontOfSize:14*VerticalTexeRatio()];
        [cell addSubview:label];
        cell.choseButton.hidden = YES;
        cell.choseupButton.hidden = YES;
    }else{
        if (indexPath.section == 0 && _type!=3) {
            cell.choseButton.selected = YES;
            _bankIndex = indexPath;
        }
        if (_type == 3 && indexPath.section == 0&&indexPath.row==1) {
            cell.choseButton.selected = YES;
            _bankIndex = indexPath;
        }
        NSString * name = [NSString stringWithFormat:@"%@",_banksInfoArray[indexPath.section][indexPath.row-1][@"image"]];
        if ([name isEqualToString:@"pay1"]) {
            cell.bankImage.frame = flexibleFrame(CGRectMake(16, 10, 21, 28), NO);
        }else if ([name isEqualToString:@"pay2"]){
            cell.bankImage.frame = flexibleFrame(CGRectMake(10, 10, 41, 26), NO);
        }else if ([name isEqualToString:@"pay3"]){
            cell.bankImage.frame = flexibleFrame(CGRectMake(14, 9, 33, 27), NO);
        }else if ([name isEqualToString:@"pay4"]){
            cell.bankImage.frame = flexibleFrame(CGRectMake(10, 12, 34, 23), NO);
        }else {
            cell.bankImage.frame = flexibleFrame(CGRectMake(18, 8, 27, 27), NO);
        }
        cell.bankImage.image = [UIImage imageNamed:name];
        cell.bankName.text = [NSString stringWithFormat:@"%@",_banksInfoArray[indexPath.section][indexPath.row-1][@"name"]];
        if (indexPath.section == 0&&_type!=3) {
            NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@    %@元",_banksInfoArray[indexPath.section][indexPath.row-1][@"name"],_leftMoney]];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000] range:NSMakeRange(str.length-_leftMoney.length-5, _leftMoney.length+5)];
            cell.bankName.attributedText = str;
        }
       
        cell.choseBlock = ^(NSString * str){
            if ([str isEqualToString:@"1"]) {
                PayTableViewCell * payCell = [_tableView cellForRowAtIndexPath:_bankIndex];
                payCell.choseButton.selected = NO;
                payCell.choseupButton.selected = NO;
                
                PayTableViewCell * PayCell = [_tableView cellForRowAtIndexPath:indexPath];
                PayCell.choseButton.selected = YES;
                PayCell.choseupButton.selected = YES;
                _bankIndex = indexPath;
            }else{
                _bankIndex = nil;
            }
        };
    }
    
    return cell;
    
}

#pragma   mark  ======================================
#pragma   mark GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    self.view.userInteractionEnabled = YES;
    
    if (tag==SX_payOrderTag) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
                PaySuccessViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PaySuccess"];
                page.indentId = _payId;
                page.payTypeStr = _banksInfoArray[_bankIndex.section][_bankIndex.row][@"name"];
                page.payMoney = _payOrderPrice;
                [self.navigationController   pushViewController:page animated:YES];

            });
            
        }
    }else if (tag == SX_getAlipayInfoTag){
        //支付宝配置信息
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableDictionary *data = [NSMutableDictionary dictionary];
                 [data setObject:database[@"result"][@"payMchId"] forKey:@"payPartner"];
                 [data setObject:database[@"result"][@"payAppId"] forKey:@"paySellAccount"];
                [data setObject:database[@"result"][@"payPrivateKey"] forKey:@"payPrivate"];
                [data setObject:database[@"result"][@"payNotifyUrl"] forKey:@"AlipayNotifyUrl"];
                    //支付宝
                    [self userAlibabaPaymentClick:data];
            });
            
        }
    }else if(tag == SX_getWxpayInfoTag){
        //微信配置信息
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *payDta = [database objectForKey:@"result"];
                //微信
                [self sendPay_demo:payDta];
            });
            
        }
    }else if (tag == SX_SX_getEpurse){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _leftMoney = [NSString stringWithFormat:@"%.2f",[database[@"result"][@"epurse"]floatValue]];
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
            PayTableViewCell * cell =[ _tableView cellForRowAtIndexPath:indexPath];
            NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@    %@元",_banksInfoArray[indexPath.section][indexPath.row-1][@"name"],_leftMoney]];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000] range:NSMakeRange(str.length-_leftMoney.length-5, _leftMoney.length+5)];
            cell.bankName.attributedText = str;
        }
        
    }else if (tag == SX_SX_payOrderByEpurse){
    
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _passwordField.text = @"";
            _maskView.hidden = YES;
            _passwordView.hidden = YES;
            [self hideKeyBoard];
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:2];
            [self.navigationController  popViewControllerAnimated:YES];
        }
    
    }else if (tag == SX_SX_getAlipayInfo){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableDictionary *data = [NSMutableDictionary dictionary];
                [data setObject:database[@"result"][@"payMchId"] forKey:@"payPartner"];
                [data setObject:database[@"result"][@"payAppId"] forKey:@"paySellAccount"];
                [data setObject:database[@"result"][@"payPrivateKey"] forKey:@"payPrivate"];
                [data setObject:database[@"result"][@"payNotifyUrl"] forKey:@"AlipayNotifyUrl"];
                //支付宝
                [self userAlibabaPaymentClick:data];
            });
            
        }
    
    }else if (tag == SX_SX_getWxpayInfo){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableDictionary *data = database[@"result"];
                //微信
                [self sendPay_demo:data];
            });
            
        }
    }

}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    self.view.userInteractionEnabled = YES;
    
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"hadPay" object:@"1"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
